package x.ovo.wechat.bot.http;

import lombok.Getter;
import lombok.NonNull;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

import java.net.HttpCookie;
import java.util.*;

public class OkCookieJar implements CookieJar {

    @Getter
    private static final Map<String, List<Cookie>> cookieStore = new HashMap<>();

    @Override
    public @NonNull List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url.host());
        return cookies != null ? cookies : Collections.emptyList();
    }

    @Override
    public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {
        cookieStore.put(httpUrl.host(), list);
    }

    public List<HttpCookie> getCookies() {
        return cookieStore.values()
                .stream()
                .flatMap(Collection::stream)
                .map(Cookie::toString)
                .map(HttpCookie::parse)
                .flatMap(Collection::stream)
                .toList();
    }

    public static void reverse(Map<String, List<Cookie>> cookies) {
        cookieStore.putAll(cookies);
    }
}
